var crypto = require('crypto');
var _ = require('lodash');
var logger = require('../lib/logger');
var WechatService = require('../service/wechat').WechatService
var resErr = require('../lib/util.js').resErr;
var moment = require('moment');
var shortid = require('shortid');
var config = require('../lib/config');
var querystr = require('querystring');
var UserService = require("../service/user").UserService;
var async = require('async');

exports.token_verify = function(req,res){
  logger.info("Wechat callback !!!!");
  var signature = req.param("signature");
  var timestamp = req.param("timestamp");
  var nonce = req.param("nonce");
  var echostr = req.param("echostr");
  var token = "foxtail";
  
  var arrs = [];
  arrs.push(token);
  arrs.push(timestamp);
  arrs.push(nonce);

  arrs = _.sortBy(arrs);
  
  var content = arrs.join("");
  var sha1 = crypto.createHash('sha1');
  sha1.update(content);
  var decrypedStr = sha1.digest('hex');

  logger.info("signature...");
  logger.info(signature);
  logger.info("decrypedStr...");
  logger.info(decrypedStr);

  res.end(echostr);
}


// 根据code，获取token
exports.oauth2_callback = function(req,res){
  var result = {};
  result.code = req.param("code");
  result.url = req.param("state");
  var ws = new WechatService();
  var us = new UserService();
  logger.info("oauth2 callback!!!");
  logger.info("code : " + result.code);
  logger.info("state :" + result.url);

  var token = null;
  async.waterfall([
    function(cb){      
      ws.getAccessTokenByCode(req.param("code"),function(err,_token){
        if(err) return cb(err);
        token = _token;
        return cb(null);
      })
    },function(cb){
      var openid = token.openid;
      logger.info("openid : " + openid);
      ws.getUserInfo(openid,function(err,userinfo){
        if(err) return cb(err);
        req.session.user_fw = {};
        req.session.user_fw.openid = openid;
        req.session.user_fw.wx = userinfo;
        logger.info("wechat user info");
        logger.info(userinfo);
        return cb(null);
      })
    },function(cb){
      var openid = token.openid;
      us.getUserByOpenid(openid,function(err,user){
        if(err) return cb(err);
        req.session.user_fw.user = user;
        return cb(null);
      })
    }
  ],function(err){
    if(err){
      return resErr(res,err);
    }
    if(req.param("state")){
      var url = decodeURIComponent(req.param("state"));
      return res.redirect(url);
    }else{
      return res.render('/test');
    }
  })
}

exports.get_access_token = function(req,res){
  var ws = new WechatService();
  ws.getAccessToken(function(err,access_token){
    if(err){
      return resErr(res,err);
    }
    return res.end(access_token);
  })
}

exports.send_tpl_msg_test = function(req,res){
  var open_id = req.param("open_id") || "okFmRsw5IqC-wCpGou1-drj5i4v0";
  var data = {};
  data.name = 'redone测试消息推送';
  data.dt = new Date().toString();
  data.msg = 'hello world!';
  var ws = new WechatService();
  // var url = "http://120.55.161.206/rest/company/qrcode?uuid=Vk09FS3dg&type=image";
  var url = "http://www.gf.com.cn";
  ws.sendTplMsg("tpl_verify",open_id,url,data,function(err){
    if(err) return resErr(res,err);
    return res.json({"success":true});
  })
}

exports.get_jsapi_ticket = function(req,res){
  var ws = new WechatService();
  ws.getJsapiTicket(function(err,ticket){
    return res.json(ticket);
  });
}

exports.get_signature_by_url = function(req,res){
  var url = req.param("url");
  if(!url){
    return resErr(res,'url不得为空！');
  }
  url.substr(0,url.indexOf("#"));
  var ws = new WechatService();
  ws.getJsapiTicket(function(err,jsapi_ticket){
    if(err) return resErr(res,err);
    var timestamp = moment().format('X');
    var arrs = [];
    var url = req.param("url");
    var nonceStr = shortid.generate();
    var content = "";
    content = "jsapi_ticket=" + jsapi_ticket;
    content += "&noncestr=" + nonceStr;
    content += "&timestamp=" + timestamp;
    content += "&url=" + decodeURIComponent(url);
    logger.info(content);
    var sha1 = crypto.createHash('sha1');
    sha1.update(content);
    var encrypedStr = sha1.digest('hex');
    var result = {};
    result.signature = encrypedStr;
    result.nonceStr = nonceStr;
    result.timestamp = timestamp;
    result.appId = config.wechat.appid;
    result.jsapi_ticket = jsapi_ticket;
    logger.info(result);
    return res.json(result);
  });
}

exports.download_image = function(media_id){
  var ws = new WechatService();
  ws.getAccessToken(function(err,access_token){
    if(err){
      return resErr(res,err);
    }
    return res.end(access_token);
  })
}

exports.wechat_user_info = function(req,res){
  var openid = req.param("openid");
  if(!openid) return resErr(res,'openid不得为空');
  var ws = new WechatService();
  ws.getUserInfo(openid,function(err,userInfo){
    if(err) return resErr(res,err);
    return res.json(userInfo);
  })
}